<template>
  <div>
    <!--  面包屑  -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片  -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <!--   搜索添加   -->
          <el-input @clear="getUserList"
                    clearable
                    v-model="queryInfo.query"
                    placeholder="请输入内容"
                    class="input-with-select">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--   用户列表   -->
      <el-table
        border
        stripe
        :data="userList"
        style="width: 100%">
        <el-table-column
          align="center"
          type="index">
        </el-table-column>
        <el-table-column
          prop="username"
          align="center"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="email"
          align="center"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="mobile"
          align="center"
          label="电话">
        </el-table-column>
        <el-table-column
          prop="role_name"
          align="center"
          label="角色">
        </el-table-column>
        <el-table-column
          align="center"
          label="状态">
          <template slot-scope="scope">
            <el-switch
              @change="userStateChage(scope.row)"
              v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="200px"
          label="操作">
          <template slot-scope="scope">
            <span style="display: none">{{scope.row.id}}</span>
            <!--      修改      -->
            <el-button @click="showOpenUpdate(scope.row.id)"
                       type="primary"
                       icon="el-icon-edit"
                       size="small"></el-button>
            <!--     分配角色       -->
            <el-tooltip :enterable="false"
                        effect="dark"
                        content="分配角色"
                        placement="top-start">
              <el-button type="warning"
                         @click="setRole(scope.row)"
                         icon="el-icon-setting"
                         size="small"></el-button>
            </el-tooltip>
            <!--      删除      -->
            <el-button @click="delUser(scope.row.id)"
                       type="danger"
                       icon="el-icon-delete"
                       size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--   分页   -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--  添加用户对话框  -->
    <el-dialog
      @close="addDialogClosed"
      title="添加用户"
      :visible.sync="addUserVisible"
      width="50%">
      <!--   主体区域   -->
      <el-form :model="addFromUser"
               :rules="addFromUserRules"
               ref="addFromUserRef"
               label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFromUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFromUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFromUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFromUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--  修改用户对话框  -->
    <el-dialog
      @close="updateDialogClosed"
      title="修改用户"
      :visible.sync="updateFromUserRef"
      width="50%">
      <!--   主体区域   -->
      <el-form :model="updateFromUser" :rules="addFromUserRules" ref="updateFromUserRef"
               label-width="70px">
        <el-form-item label="用户名">
          <el-input :disabled="true" v-model="updateFromUser.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateFromUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="updateFromUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateFromUserRef = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--  分配角色对话框  -->
    <el-dialog
      @close="setRoleDialogClose"
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%">
      <!--   主体区域   -->
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <br>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <br>
        <p>分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!--   按钮区域   -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>export default {
  name: 'Users',
  data () {
    // 自定义邮箱验证规则
    let checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        // 合法
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义手机号验证规则
    let checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      // 用户列表参数
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前显示多少条数据
        pagesize: 10
      },
      // 列表数据
      userList: [],
      total: 0,
      // 对话框
      addUserVisible: false,
      updateFromUserRef: false,
      // 分配角色对话框
      setRoleDialogVisible: false,
      // 展示对应用户角色信息
      userInfo: {},
      // 角色信息
      rolesList: [],
      // 选中的角色ID
      selectedRoleId: '',
      // 根据ID查询用户数据
      updateFromUser: {
        username: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单
      addFromUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单校验
      addFromUserRules: {
        username: [
          {
            required: true, message: '请输入用户名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'
          }
        ],
        email: [
          {
            required: true, message: '请输入邮箱', trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请输入手机号', trigger: 'blur'
          },
          {
            validator: checkMobile, trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    // 用户列表请求
    getUserList () {
      this.$http.get('users', { params: this.queryInfo }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.userList = res.data.data.users
        this.total = res.data.data.total
      })
    },
    // 最新页码数
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听状态
    userStateChage (value) {
      this.$http.put(`users/${value.id}/state/${value.mg_state}`).then(res => {
        if (res.data.meta.status !== 200) {
          value.mg_state = !value.mg_state
          return this.$message.error('更新用户状态失败!')
        }
        this.$message.success('更新用户状态成功!')
      })
    },
    // 监听对话框关闭
    addDialogClosed () {
      this.$refs.addFromUserRef.resetFields()
    },
    // 添加新用户
    addUser () {
      this.$refs.addFromUserRef.validate(valid => {
        if (!valid) return
        this.$http.post('users', this.addFromUser).then(res => {
          if (res.data.meta.status !== 201) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.addUserVisible = false
          this.getUserList()
        })
      })
    },
    // 弹出修改对话框
    showOpenUpdate (id) {
      this.$http.get('users/' + id).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.updateFromUser = res.data.data
        this.updateFromUserRef = true
      })
    },
    // 监听修改对话框
    updateDialogClosed () {
      this.$refs.updateFromUserRef.resetFields()
    },
    // 修改用户
    updateUser () {
      this.$refs.updateFromUserRef.validate(valid => {
        if (!valid) return
        this.$http.put('users/' + this.updateFromUser.id, {
          email: this.updateFromUser.email,
          mobile: this.updateFromUser.mobile
        }).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.updateFromUserRef = false
          this.getUserList()
        })
      })
    },
    // 删除用户
    delUser (id) {
      this.$alert('确定删除吗', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        this.$http.delete('users/' + id).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          this.getUserList()
        })
      }).catch(err => err)
    },
    // 展示分配角色对话框
    setRole (userInfo) {
      this.userInfo = userInfo
      // 展示对话框钱获取所有角色列表
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.rolesList = res.data.data
      })
      this.setRoleDialogVisible = true
    },
    // 分配角色
    setRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      }).then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg)
        }
        this.$message.success(res.data.meta.msg)
        this.getUserList()
        this.setRoleDialogVisible = false
      })
    },
    // 监听关闭角色对话框
    setRoleDialogClose () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
